package com.nd.service.wx;

import com.nd.dao.*;
import com.nd.pojo.bean.*;

import com.nd.pojo.bo.wx.CartCheckOutBo;
import com.nd.pojo.vo.wx.CartCheckedVo;
import com.nd.pojo.vo.wx.CartCheckoutVo;
import com.nd.pojo.vo.wx.CartIndexVo;
import com.nd.pojo.vo.wx.CartTotalVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;

    @Override
    public CartIndexVo queryCarIndexVo() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(user.getId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        for (Cart cart : carts) {
            goodsCount = goodsCount + cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice().multiply((new BigDecimal(cart.getNumber()))));
            if (cart.getChecked()) {
                checkedGoodsCount = checkedGoodsCount + cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
        CartTotalVo cartTotalVo = new CartTotalVo(goodsCount, checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        return new CartIndexVo(cartTotalVo, carts);
    }

    @Override
    public Integer addToCart(Cart cart) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        Date now = new Date();
        Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        GoodsProduct product = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andProductIdEqualTo(cart.getProductId()).andDeletedEqualTo(false).andUserIdEqualTo(user.getId());
        List<Cart> checkCarts = cartMapper.selectByExample(cartExample);
        if (checkCarts.size() > 0) {
            Cart checkCart = checkCarts.get(0);
            Short number = checkCart.getNumber();
            checkCart.setNumber((short) (number + checkCart.getNumber()));
            checkCart.setAddTime(now);
            checkCart.setUpdateTime(now);
            int update = cartMapper.updateByPrimaryKeySelective(checkCart);
            if (update == 0) return null;
            CartIndexVo cartIndexVo = queryCarIndexVo();
            return cartIndexVo.getCartTotal().getGoodsCount();
        }
        cart.setUserId(user.getId());
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setPicUrl(product.getUrl());
        if (cart.getNumber() > product.getNumber()) return product.getNumber();
        cart.setAddTime(now);
        cart.setUpdateTime(now);
        int insertRow = cartMapper.insertSelective(cart);
        if (insertRow == 0) return null;
        CartIndexVo cartIndexVo = queryCarIndexVo();
        return cartIndexVo.getCartTotal().getGoodsCount();
    }

    @Override
    public Integer fastAddToOrder(Cart cart) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        Date now = new Date();
        Goods goods = goodsMapper.selectByPrimaryKey(cart.getGoodsId());
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        GoodsProduct product = goodsProductMapper.selectByPrimaryKey(cart.getProductId());
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andProductIdEqualTo(cart.getProductId()).andDeletedEqualTo(false).andUserIdEqualTo(user.getId());
        List<Cart> checkCarts = cartMapper.selectByExample(cartExample);
        if (checkCarts.size() > 0) {
            //购物车有这个商品
            Cart checkCart = checkCarts.get(0);
            //如果是立即购买，购物车中已经有了这个商品，直接将购物车的商品对象返回
            checkCart.setNumber(cart.getNumber());
            checkCart.setAddTime(now);
            checkCart.setUpdateTime(now);
            int update = cartMapper.updateByPrimaryKeySelective(checkCart);
            if (update == 0) return null;
            return checkCart.getId();
        }
        //购物车没有这个商品
        cart.setUserId(user.getId());
        cart.setPrice(product.getPrice());
        cart.setSpecifications(product.getSpecifications());
        cart.setPicUrl(product.getUrl());
        cart.setAddTime(now);
        cart.setUpdateTime(now);
        int insertRow = cartMapper.insertSelective(cart);
        if (insertRow == 0) return null;
        return cartMapper.selectKey();
    }

    @Override
    public CartIndexVo checked(CartCheckedVo cartCheckedVo) {

        Integer[] productIds = cartCheckedVo.getProductIds();
        for (Integer productId : productIds) {
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andProductIdEqualTo(productId).andDeletedEqualTo(false);
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            for (Cart cart : carts) {
                cart.setChecked(cartCheckedVo.getIsChecked() != 0);
                int i = cartMapper.updateByPrimaryKeySelective(cart);
                if (i == 0) return null;
            }
        }
        return queryCarIndexVo();
    }

    @Override
    public Integer updateCart(Cart cart) {
        Date now = new Date();
        cart.setUpdateTime(now);
        if(cart.getNumber() <= 0){
            cart.setNumber((short) 0);
            cart.setDeleted(false);
            int delete = cartMapper.updateByPrimaryKeySelective(cart);
            if(delete == 0) return 10000;
            return 0;
        }
        int update = cartMapper.updateByPrimaryKeySelective(cart);
        if(update == 0) return 10000;
        return 0;
    }

    @Override
    public CartIndexVo deleteCarts(CartDeleteVo cartDeleteVo) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer[] productIds = cartDeleteVo.getProductIds();
        Date now = new Date();
        for (Integer productId : productIds) {
            CartExample cartExample = new CartExample();
            cartExample.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(user.getId());
            List<Cart> carts = cartMapper.selectByExample(cartExample);
            for (Cart cart : carts) {
                cart.setDeleted(true);
                cart.setUpdateTime(now);
                int delete = cartMapper.updateByPrimaryKeySelective(cart);
                if(delete == 0) return null;
            }
        }
        return queryCarIndexVo();
    }

    @Override
    public CartCheckoutVo queryCartCheckoutVo(CartCheckOutBo cartCheckOutBo) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Integer addressId = cartCheckOutBo.getAddressId();
        Integer couponId = cartCheckOutBo.getCouponId();
        Integer grouponRulesId = cartCheckOutBo.getGrouponRulesId();
        Address checkedAddress = null;
        if(addressId == 0){
            AddressExample addressExample = new AddressExample();
            addressExample.createCriteria().andUserIdEqualTo(user.getId()).andIsDefaultEqualTo(true);
            List<Address> addresses = addressMapper.selectByExample(addressExample);
            if(addresses.size()>0){
                checkedAddress = addresses.get(0);
                addressId = checkedAddress.getId();
            }
        }else {
            checkedAddress = addressMapper.selectByPrimaryKey(addressId);
        }
        BigDecimal grouponPrice = new BigDecimal(0);
        BigDecimal actualPrice = new BigDecimal(0);
        BigDecimal orderTotalPrice = new BigDecimal(0);
        BigDecimal couponPrice = new BigDecimal(0);
        BigDecimal availableCouponLength = new BigDecimal(0);
        BigDecimal freightPrice = new BigDecimal(8);
        BigDecimal goodsTotalPrice = new BigDecimal(0);
        GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);
        //获取团购优惠金额
        if(grouponRules != null){
            grouponPrice = grouponRules.getDiscount();
        }
        //获取优惠券金额
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        if(coupon != null){
            couponPrice = coupon.getDiscount();
        }
        //查询客户所有选中的购物车的商品
        List<Cart> checkedGoodsList = new ArrayList<>();
        //如果传过来了cartId不等于0,就是立即购买进来的
        Integer cartId = cartCheckOutBo.getCartId();
        if(cartId != 0){
            Cart cart = cartMapper.selectByPrimaryKey(cartId);
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice()).multiply(new BigDecimal(cart.getNumber()));
            checkedGoodsList.add(cart);
        }else {
            //如果传过来的cartId=0,就是在购物车批量下单
            CartExample cartExample = new CartExample();
            CartExample.Criteria criteria = cartExample.createCriteria();
            criteria.andDeletedEqualTo(false).andUserIdEqualTo(user.getId()).andCheckedEqualTo(true);
            checkedGoodsList = cartMapper.selectByExample(cartExample);
            for (Cart cart : checkedGoodsList) {
                //获取商品总额
                goodsTotalPrice = goodsTotalPrice.add(cart.getPrice()).multiply(new BigDecimal(cart.getNumber()));
            }
        }
        if (goodsTotalPrice.doubleValue() >= 88) {
            //商品总额满88免运费
            freightPrice = new BigDecimal(0);
        }
        //订单总额 = 商品总额+运费-团购优惠-优惠券优惠
        orderTotalPrice =
                goodsTotalPrice.add(freightPrice).
                        subtract(grouponPrice).subtract(couponPrice);
        actualPrice = orderTotalPrice;
        return new CartCheckoutVo(grouponPrice,grouponRulesId,checkedAddress,actualPrice,
                orderTotalPrice,couponPrice,availableCouponLength,
                couponId,freightPrice,goodsTotalPrice,addressId,checkedGoodsList);
    }

    @Override
    public int queryGoodsCount() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andCheckedEqualTo(false).andUserIdEqualTo(user.getId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        int goodsCount = 0;
        for (Cart cart : carts) {
            goodsCount = goodsCount + cart.getNumber();
        }
        return goodsCount;
    }
}
